#include <iostream>
#include <cstring>
using namespace std;

#include "DatabaseManager.h"
#include "UserManager.h"

UserManager::UserManager() : dbManager() {
    dbManager.connect();
}

UserManager::~UserManager() {
    dbManager.disconnect();
}

bool UserManager::registerUser(const string& username, const string& password) {
    lock_guard<mutex> lock(mutex);

    // 检查用户名是否已存在
    vector<string> results = dbManager.fetchResults("SELECT username FROM userinfo WHERE username = '" + username + "';");
    if (!results.empty()) {
        cerr << "Username already exists!" << endl;
        return false;
    }

    // 插入新用户
    string query = "INSERT INTO userinfo (username, password, role) VALUES ('" + username + "', '" + password + "', 'User');";
    if (dbManager.executeQuery(query)) {
        cout << "User registered successfully." << endl;
        return true;
    }
    return false;
}

bool UserManager::loginUser(const string& username, const string& password) {
    lock_guard<mutex> lock(mutex);

    // 获取用户信息
    vector<string> results = dbManager.fetchResults("SELECT id, password FROM userinfo WHERE username = '" + username + "';");
    if (results.empty()) {
        cerr << "User not found!" << endl;
        return false;
    }

    // 确保查询结果的字段顺序和内容正确
    if (results.size() < 2) {
        cerr << "Invalid query result!" << endl;
        return false;
    }

    int userId = stoi(results[0]);
    string storedPassword = results[1];

    cout << "User ID: " << userId << ", Stored Password: " << storedPassword << endl;

    // 比较输入的密码与存储的密码
    if (password == storedPassword) {
        users[userId] = User(userId, username, storedPassword, User::Role::User);  // 创建用户对象
        sessions[userId] = "active_session";  // 创建会话
        cout << "User logged in successfully." << endl;
        return true;
    } else {
        cerr << "Incorrect password!" << endl;
        return false;
    }
}


void UserManager::logoutUser(int userId) {
    lock_guard<mutex> lock(mutex);
    sessions.erase(userId);
    users.erase(userId);
    cout << "User logged out." << endl;
}

User* UserManager::getUser(int userId) {
    lock_guard<mutex> lock(mutex);  // 保护多线程下的数据一致性
    // 查找并返回用户信息
    cout << "Searching for user ID: " << userId << endl;
    if (users.find(userId) != users.end()) {
        cout << "Found user!" << endl;
        return &users[userId];
    }
    cerr << "User not found!" << endl;
    return nullptr;
}
